<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getNoticeListApi, createNoticeApi, updateNoticeApi, deleteNoticeApi, batchDeleteNoticeApi, updateNoticeStatusApi, updateNoticeTopApi } from "@/api/notice-manage"
import { type NoticeVo, type CreateNoticeRequest, type UpdateNoticeRequest } from "@/api/notice-manage/types/notice"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "NoticeManage"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 新增/修改公告
const DEFAULT_FORM_DATA: CreateNoticeRequest = {
  title: "",
  content: "",
  targetType: 0,
  priority: 0,
  status: 0,
  startTime: "",
  endTime: "",
  isTop: 0
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateNoticeRequest>(cloneDeep(DEFAULT_FORM_DATA))
const isUpdate = ref<boolean>(false)

const formRules: FormRules<CreateNoticeRequest> = {
  title: [{ required: true, trigger: "blur", message: "请输入公告标题" }],
  content: [{ required: true, trigger: "blur", message: "请输入公告内容" }],
  targetType: [{ required: true, trigger: "change", message: "请选择目标类型" }],
  priority: [{ required: true, trigger: "change", message: "请选择优先级" }],
  status: [{ required: true, trigger: "change", message: "请选择状态" }],
  startTime: [{ required: true, trigger: "change", message: "请选择开始时间" }],
  endTime: [{ required: true, trigger: "change", message: "请选择结束时间" }]
}

const handleCreate = () => {
  dialogVisible.value = true
  isUpdate.value = false
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const handleUpdate = (row: NoticeVo) => {
  dialogVisible.value = true
  isUpdate.value = true
  formData.value = {
    title: row.title,
    content: row.content,
    targetType: row.targetType,
    priority: row.priority,
    status: row.status,
    startTime: row.startTime || "",
    endTime: row.endTime || "",
    isTop: row.isTop
  }
  ;(formData.value as UpdateNoticeRequest).id = row.id
}

const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    
    const api = isUpdate.value ? updateNoticeApi : createNoticeApi
    api(formData.value as any)
      .then(() => {
        ElMessage.success(isUpdate.value ? "修改成功" : "创建成功")
        dialogVisible.value = false
        getNoticeData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

// 删除公告
const handleDelete = (row: NoticeVo) => {
  ElMessageBox.confirm(`正在删除公告：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteNoticeApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getNoticeData()
    })
  })
}

// 批量删除
const multipleTableRef = ref()
const multipleSelection = ref<NoticeVo[]>([])

const handleSelectionChange = (val: NoticeVo[]) => {
  multipleSelection.value = val
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的公告")
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 个公告？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id)
    batchDeleteNoticeApi(ids).then(() => {
      ElMessage.success("批量删除成功")
      getNoticeData()
    })
  })
}

// 更新状态
const handleStatusChange = (row: NoticeVo, status: number) => {
  const statusText = status === 1 ? "启用" : "禁用"
  ElMessageBox.confirm(`确认${statusText}该公告？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    updateNoticeStatusApi(row.id, status).then(() => {
      ElMessage.success(`${statusText}成功`)
      getNoticeData()
    })
  })
}

// 更新置顶状态
const handleTopChange = (row: NoticeVo, isTop: number) => {
  const topText = isTop === 1 ? "置顶" : "取消置顶"
  ElMessageBox.confirm(`确认${topText}该公告？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    updateNoticeTopApi(row.id, isTop).then(() => {
      ElMessage.success(`${topText}成功`)
      getNoticeData()
    })
  })
}

// 查询公告数据
const noticeData = ref<NoticeVo[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  title: "",
  targetType: "",
  priority: "",
  status: "",
  isTop: ""
})

const getNoticeData = () => {
  loading.value = true
  getNoticeListApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    title: searchData.title || undefined,
    targetType: searchData.targetType ? Number(searchData.targetType) : undefined,
    priority: searchData.priority ? Number(searchData.priority) : undefined,
    status: searchData.status ? Number(searchData.status) : undefined,
    isTop: searchData.isTop ? Number(searchData.isTop) : undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      noticeData.value = data.list
    })
    .catch(() => {
      noticeData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getNoticeData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// 格式化显示
const formatTargetType = (type: number) => {
  const typeMap: Record<number, string> = {
    0: "全部端",
    1: "顾客端",
    2: "商家端",
    3: "配送端"
  }
  return typeMap[type] || "未知类型"
}

const formatPriority = (priority: number) => {
  const priorityMap: Record<number, string> = {
    0: "普通",
    1: "重要",
    2: "紧急"
  }
  return priorityMap[priority] || "未知优先级"
}

const formatStatus = (status: number) => {
  return status === 1 ? "启用" : "禁用"
}

const formatIsTop = (isTop: number) => {
  return isTop === 1 ? "是" : "否"
}

// 获取优先级标签类型
const getPriorityTagType = (priority: number): "info" | "warning" | "danger" => {
  const tagTypeMap: Record<number, "info" | "warning" | "danger"> = {
    0: "info",
    1: "warning",
    2: "danger"
  }
  return tagTypeMap[priority] || "info"
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getNoticeData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="title" label="公告标题">
          <el-input v-model="searchData.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="targetType" label="目标类型">
          <el-select v-model="searchData.targetType" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="全部端" value="0" />
            <el-option label="顾客端" value="1" />
            <el-option label="商家端" value="2" />
            <el-option label="配送端" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item prop="priority" label="优先级">
          <el-select v-model="searchData.priority" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="普通" value="0" />
            <el-option label="重要" value="1" />
            <el-option label="紧急" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item prop="isTop" label="置顶">
          <el-select v-model="searchData.isTop" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleCreate">新增公告</el-button>
          <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getNoticeData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table ref="multipleTableRef" :data="noticeData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="title" label="标题" align="center" min-width="150" show-overflow-tooltip />
          <el-table-column prop="targetType" label="目标类型" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.targetType === 0 ? 'success' : scope.row.targetType === 1 ? 'primary' : scope.row.targetType === 2 ? 'warning' : 'info'" effect="plain" disable-transitions>
                {{ formatTargetType(scope.row.targetType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" align="center" width="80">
            <template #default="scope">
              <el-tag :type="getPriorityTagType(scope.row.priority)" effect="plain" disable-transitions>
                {{ formatPriority(scope.row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="plain" disable-transitions>
                {{ formatStatus(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isTop" label="置顶" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.isTop === 1 ? 'warning' : 'info'" effect="plain" disable-transitions>
                {{ formatIsTop(scope.row.isTop) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="viewCount" label="浏览量" align="center" width="80" />
          <el-table-column prop="startTime" label="开始时间" align="center" width="160">
            <template #default="scope">
              {{ scope.row.startTime || '未设置' }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" align="center" width="160">
            <template #default="scope">
              {{ scope.row.endTime || '未设置' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
          <el-table-column fixed="right" label="操作" width="280" align="center">
            <template #default="scope">
              <el-button 
                type="primary" 
                text 
                bg 
                size="small" 
                @click="handleUpdate(scope.row)"
              >
                修改
              </el-button>
              <el-button 
                v-if="scope.row.status === 1"
                type="warning" 
                text 
                bg 
                size="small" 
                @click="handleStatusChange(scope.row, 0)"
              >
                禁用
              </el-button>
              <el-button 
                v-else
                type="success" 
                text 
                bg 
                size="small" 
                @click="handleStatusChange(scope.row, 1)"
              >
                启用
              </el-button>
              <el-button 
                v-if="scope.row.isTop === 0"
                type="warning" 
                text 
                bg 
                size="small" 
                @click="handleTopChange(scope.row, 1)"
              >
                置顶
              </el-button>
              <el-button 
                v-else
                type="info" 
                text 
                bg 
                size="small" 
                @click="handleTopChange(scope.row, 0)"
              >
                取消置顶
              </el-button>
              <el-button 
                type="danger" 
                text 
                bg 
                size="small" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isUpdate ? '修改公告' : '新增公告'"
      @closed="resetForm"
      width="800px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="left">
        <el-form-item prop="title" label="公告标题">
          <el-input v-model="formData.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item prop="content" label="公告内容">
          <el-input 
            v-model="formData.content" 
            type="textarea" 
            :rows="6" 
            placeholder="请输入公告内容" 
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="targetType" label="目标类型">
              <el-select v-model="formData.targetType" placeholder="请选择目标类型" style="width: 100%">
                <el-option label="全部端" :value="0" />
                <el-option label="顾客端" :value="1" />
                <el-option label="商家端" :value="2" />
                <el-option label="配送端" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="priority" label="优先级">
              <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="普通" :value="0" />
                <el-option label="重要" :value="1" />
                <el-option label="紧急" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="status" label="状态">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="isTop" label="是否置顶">
              <el-select v-model="formData.isTop" placeholder="请选择是否置顶" style="width: 100%">
                <el-option label="否" :value="0" />
                <el-option label="是" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="startTime" label="开始时间">
              <el-date-picker
                v-model="formData.startTime"
                type="datetime"
                placeholder="请选择开始时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="endTime" label="结束时间">
              <el-date-picker
                v-model="formData.endTime"
                type="datetime"
                placeholder="请选择结束时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>